package com.dtkavin.threads;

/**
 * Created by john on 10/3/16.
 * 线程范围的共享，线程间不共享
 */

public class ThreadLocalDemo {
    public void threadRun1() {
        new Thread(new Runnable() {
            public void run() {
                ThreadData instance = ThreadData.getInstance();
                instance.setName("aaa");
                System.out.println(instance.getName());
            }
        }).start();
    }

    public void threadRun2() {
        new Thread(new Runnable() {
            public void run() {
                ThreadData instance = ThreadData.getInstance();
                instance.setName("bbb");
                System.out.println(instance.getName());
            }
        }).start();
    }


}

class ThreadData {
    private String name;
    private int age;

    private static ThreadLocal<ThreadData> map = new ThreadLocal<ThreadData>();

    private ThreadData() {
    }


    public static /*synchronized*/ ThreadData getInstance() {//单例要考虑多线程问题，但是此处多线程对互斥没有要求
        ThreadData data = map.get();
        if (data == null) {
            data = new ThreadData();
            map.set(data);
        }
        return data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}